import {
  getImage,
  getPage
} from '../../utils/config';
import {
  promisify,
  $empty,
  storage,
  $toast,
  http,
  Validate
} from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import api from '../../utils/api';
const app = getApp();

Page({

  data: {
    guid: "",
    scene: {},
    logged: 0, //判断是否登录 0未登录 1已登录
    logoImg: getImage.logo,
    wechatImg: getImage.wechat,
    pwIcon: 'eye-o',
    pwType: false,
    smsCode: '',
    checked: true,
    smsCodeBtn: false,
    smsCodeText: '获取验证码',
    loginSwitchType: 1,
    loginSwitchText: '账号密码登录',
    list: {},
    radio: 0,
    //userForm
    userForm: {
      userName: '',
      password: '',
    },
    //phoneForm
    phoneForm: {
      phoneNumber: '',
      smsCode: '',
    },
    navbar: {},
    isShowPlayButton: false
  },



  /**
   * 手机注册
   */
  gom() {
    wxApi.navigateTo(getPage.reguser + "?guid=" + this.data.guid);
  },

  onChange(event) {
    this.setData({
      checked: event.detail
    });
  },

  /**
   * 切换登录方式
   */
  loginSwitch(e) {
    console.log(e.currentTarget.dataset.id);
    this.setData({
      loginSwitchType: e.currentTarget.dataset.id,
    })
    // if (this.data.loginSwitchType) {
    //   this.setData({
    //     loginSwitchType: false,
    //     loginSwitchText: '手机优惠码登录',
    //   })
    // } else {
    //   this.setData({
    //     loginSwitchType: true,
    //     loginSwitchText: '短信验证登录',
    //   })
    // }
  },

  /**
   * 密码切换显示
   */
  pwChange() {
    if (this.data.pwType) {
      this.setData({
        pwIcon: 'eye-o',
        pwType: false,
      })
    } else {
      this.setData({
        pwIcon: 'closed-eye',
        pwType: true,
      })
    }
  },

  /**
   * 用户名input
   */
  userNameInput(event) {
    this.setData({
      userNameError: '',
      'userForm.userName': $empty(event.detail)
    });
  },

  /**
   * 密码input
   */
  passwordInput(event) {
    this.setData({
      passwordError: '',
      'userForm.password': $empty(event.detail)
    });
  },

  showdingyue() {
    wx.requestSubscribeMessage({
      tmplIds: ['TOqslhth-Mi9dZCm6xzdFDq0dsLdA91jxiF8qoFaebU'],
      success(res) {}
    });

  },

  /**
   * 用户名/密码登录提交form
   */
  userFormSubmit(e) {
    if (this.data.checked) {
      const {
        value
      } = e.detail;
      const {
        userForm,
        logged
      } = this.data;
      Validate.check(this, this.userValidate, value, (res) => {
        if (!res || logged) {
          return false;
        }

        http.post(api.default, {
          data: {
            action: 'login_guid',
            username: userForm.userName,
            guid: userForm.password,
          }
        }).then((res) => {
          const {
            data
          } = res.data;
          if (res.data.code == 0) {
            //登录成功存储用户信息
            app.setLogon(data, 1, () => {
              //登录后跳转
              $toast(`登录成功`, {
                icon: 'success',
                times: 1000,
              }).then(() => {
                if (data.bindwx == 1)
                  wxApi.switchTab(getPage.user);
                // wxApi.navigateTo(getPage.wx + "?uid=" + data.user.user_id);
                else
                  wxApi.switchTab(getPage.home);
                //wxApi.refreshPage();
              })
            });
          } else {
            $toast(res.errmsg);
          }
          // if (data.bindwx == 0) {
          //   //登录成功存储用户信息
          //   app.setLogon(data, 1, () => {
          //     //登录后跳转
          //     $toast(`登录成功`, {
          //       icon: 'success',
          //       times: 1000,
          //     }).then(() => {
          //       wxApi.refreshPage();
          //     })
          //   });
          // } else {
          //   //跳转绑定微信
          //   wxApi.navigateTo(getPage.wechat, {
          //     id: data.user.user_id
          //   });
          // }
        });
      });
    } else {
      $toast("请勾选同意以下协议");

    }

  },

  /**
   * 手机号码 input
   */
  phoneNumberInput(event) {
    this.setData({
      phoneNumberError: '',
      'phoneForm.phoneNumber': $empty(event.detail)
    });
  },

  /**
   * 手机短信验证码 input
   */
  smsCodeInput(event) {
    this.setData({
      smsCodeError: '',
      'phoneForm.smsCode': $empty(event.detail)
    });
  },

  /**
   * 手机号/短信码登录 form
   */
  phoneFormSubmit(e) {
    const {
      value
    } = e.detail;
    const {
      logged,
      phoneForm
    } = this.data;

    Validate.check(this, this.phoneValidate, value, (res) => {
      if (!res && !logged) {
        return false;
      }
      var pid = 0;
      if (app.pid > 0)
        pid = app.pid;
      //判断是否登录
      http.post(api.default, {
        data: {
          action: 'login_msg',
          mobile: phoneForm.phoneNumber,
          code: phoneForm.smsCode,
          pid: pid,
          guid: this.data.guid
        }
      }).then((res) => {
        const {
          data
        } = res.data;
        if (res.data.code == 0) {
          //登录成功存储用户信息
          app.setLogon(data, 1, () => {
            //登录后跳转
            $toast(`登录成功`, {
              icon: 'success',
              times: 1000,
            }).then(() => {
              if (data.bindwx == 1)
                wxApi.switchTab(getPage.user);
              // wxApi.navigateTo(getPage.wx + "?uid=" + data.user.user_id);
              else
                wxApi.switchTab(getPage.home);
              //wxApi.refreshPage();
            })
          });
        } else {
          $toast(res.errmsg);
        }
        // if (data.bindwx == 0) {
        //   //登录成功存储用户信息
        //   app.setLogon(data, 1, () => {
        //     //登录后跳转

        //     $toast(`登录成功`, {
        //       icon: 'success',
        //       times: 1000,
        //     }).then(() => {
        //       wxApi.refreshPage();
        //     })
        //   });
        // } else {
        //   //跳转绑定微信
        //   wxApi.navigateTo(getPage.wechat, {
        //     id: data.user.user_id
        //   });
        // }
      });
    });
  },

  /**
   * 获取手机验证码
   */
  getSmsCode() {
    const {
      phoneNumber
    } = this.data.phoneForm;

    Validate.rules("#phoneNumber", (res) => {
      Validate.check(this, res, {
        'phoneNumber': phoneNumber
      }, (rs, err) => {
        if (!rs) {
          $toast(err[0].msg);
          return false;
        }

        http.post(api.default, {
          data: {
            action: 'login_sms',
            mobile: phoneNumber,
          }
        }).then((res) => {
          var times = 60;
          var countInter = setInterval(() => {
            if (times >= 1) {
              times--;
              this.setData({
                smsCodeTimes: times
              });
            } else {
              /**
               * 获取过期
               */
              this.setData({
                smsCodeBtn: false,
                smsCodeText: '重新获取',
                smsCodeTimes: '',
              });
              clearInterval(countInter);
            }
          }, 1000);
          this.setData({
            smsCodeBtn: true,
            smsCodeText: ' 秒后重发',
            smsCodeTimes: 60,
          });
          //提示短信发送成功
          $toast('短信发送成功，请注意查收');
        });
      }, false);
    });
  },

  /**
   * 跳转重置密码
   */
  goPagesReset() {
    wxApi.navigateTo(getPage.reset);
  },
  onChange(event) {
    console.log(event);
    this.setData({
      radio: event.detail,
    });
  },

  // 测试
  deepdata(list){
    console.log('llllllllll',list)
    let arr = list.split('.')
    console.log('arrrrr',arr)
    arr.forEach(item=>{
      if(item.length>0){
        console.log('iiiiiiiiiiiiiit',item)
        // this.deepdata(item)
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //获取system信息
    promisify(wx.getSystemInfo)().then(res => {
      //获取右上角胶囊信息
      this.setData({
        navbar: wx.getMenuButtonBoundingClientRect(),
        window: res,
      })
    });
    storage.get('qudao').then((res) => {
      // 渠道进来
      console.log('quddddddddddddddd===', res)
      this.setData({
        qudao: res
      })
    }).catch(err => {
      console.log('errrrrrrrrrrrrrrr', err)
    })
    storage.get('click_id').then((res) => {
      // 渠道进来
      console.log('click_id===', res)
      this.setData({
        click_id: res
      })
    }).catch(err => {
      console.log('click_id-errrrrrrrrrrrrrrr', err)
    })
    const scene = decodeURIComponent(options.scene);
    // if (app.pid > 0) {
    //   //pid = app.pid;
    //   console.log(app.pid)
    // } else {
    //   app.pid = 10;

    // }
    if (options.scene) {
      const array = scene.split('=');
      if (array[0] == "guid") {
        this.setData({
          guid: array[1]
        })
      }
    }
    console.log(this.data.guid);
    /**
     * 页面参数
     */
    if (JSON.stringify(options) !== '{}') {
      if (options.guid) {
        this.setData({
          guid: options.guid
        })
        console.log(options.guid);
      }
      if (options.ucid) {
        this.setData({
          ucid: options.ucid
        })
        console.log('llllllllllllog-----options====',options.ucid);
      }
    }

    //判断是否登录
    app.getLogin().then(res => {
      this.setData({
        logged: res
      });
      this.setData({
        localInfo: res,
        userId: res.data.user.user_id,
        userRank: res.data.user.user_rank,
      });
      console.log(this.data.userId);
      if (options.web) {
        //网页自动登录
        wxApi.navigateTo("/pages/web/web?id=https://m.zhiai888.com/badun/login/" + this.data.userId);
      } else if (res.data.user.user_id > 0)
        wxApi.navigateBack(1);
    }).catch(res => {
      this.setData({
        logged: res
      })
    });

    //获取协议地址
    http.get(api.default, {
      data: {
        action: 'getreginfo'
      }
    }, false).then((res) => {
      const {
        data
      } = res.data;
      console.log(data);
      this.setData({
        list: data.data,
        bgurl: data.bgurl,
      });
      // this.deepdata(data.bgurl)
    });

    /**
     * 用户名称登录
     */
    Validate.rules("#userName,#password", (res) => {
      this.userValidate = res;
    });

    /**
     * 手机登录切换后获取数据
     */
    Validate.rules("#phoneNumber,#smsCode", (res) => {
      this.phoneValidate = res;
    });
    this.wxlogin();
  },

  wxlogin() { //获取用户的openID和sessionKey

    var that = this;
    wx.login({
      //获取code 使用wx.login得到的登陆凭证，用于换取openid
      success: (res1) => {
        console.log(res1)
        http.post(api.default, {
          data: {
            action: 'getweixininfo',
            code: res1.code
          }
        }).then((res) => {
          this.setData({
            session_key: res.data.data.session_key,
            openid: res.data.data.openid,
          });
        });
      }
    });
  },

  noSelectRadio() {
    return $toast("请勾选同意用户服务协议");
  },

  getPhoneNumber(e) { //点击获取手机号码按钮
    var that = this;
    var guid = that.data.guid;
    var pid = 0;
    //$toast(app.pid)
    if (app.pid > 0)
      pid = app.pid;
    if (that.data.radio == 1) {
      //$toast("app.pid=" + app.pid + "，pid=" + pid);
      wx.checkSession({
        success: function () {
          console.log(that.data);
          var session_key = that.data.session_key;
          var openid = that.data.openid;
          if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
            that.setData({
              modalstatus: true
            });
          } else { //同意授权
            let parms = {
              action: 'GetWXPhoneNumber',
              guid: guid,
              openid: openid,
              session_key: session_key,
              aesIv: e.detail.iv,
              encryptedData: e.detail.encryptedData,
              pid: pid
            }
            if (that.data.qudao) parms.qudao = that.data.qudao;
            if (that.data.click_id) parms.click_id = that.data.click_id;
            http.post(api.default, {
              data: parms
            }).then((res) => {
              const {
                data
              } = res.data;
              if (res.data.code == 0) {
                console.log(data);
                //登录成功存储用户信息
                app.setLogon(data, 1, () => {
                  //登录后跳转

                  $toast(`登录成功`, {
                    icon: 'success',
                    times: 1000,
                  }).then(() => {
                    if (data.bindwx == 1)
                      wxApi.switchTab(getPage.user);
                    // wxApi.navigateTo(getPage.wx + "?uid=" + data.user.user_id);
                    else{
                      if (that.data.qudao == 8) {
                        console.log('that.data.qudao == 8',that.data.qudao == 8)
                        const pages = getCurrentPages()[getCurrentPages().length - 2];
                        //返回上一页
                        wx.navigateBack({
                          delta: 1,
                          success() {
                            if (pages !== undefined || pages !== null) {
                              pages.onLoad();
                            }
                          },
                        });
                      }else{
                        if(that.data.ucid){
                          wxApi.redirectTo(getPage.hexiao, {
                            id: that.data.ucid
                        });
                        }else{
                          wxApi.switchTab(getPage.home);
                        }
                      }
                    }
                    //wxApi.refreshPage();
                  })
                });
              } else {
                $toast(res.errmsg);
              }
            });
          }
        },
        fail: function () {
          $toast("session_key 已经失效，需要重新执行登录流程");
          that.wxlogin(); //重新登录
        }
      });
    } else {
      $toast("请勾选同意用户服务协议");
      return false;
    }
  },
  gohome() {
    wxApi.switchTab(getPage.home);
  },

  // getPhoneNumber(e) {
  //   var guid = this.data.guid;
  //   var pid = 0;
  //   if (app.pid > 0)
  //     pid = app.pid;
  //   wx.login({
  //     success(res) {
  //       if (res.code) {
  //         http.post(api.default, {
  //           data: {
  //             action: 'GetPhoneNumber',
  //             guid: guid,
  //             code: res.code,
  //             aesIv: e.detail.iv,
  //             encryptedData: e.detail.encryptedData,
  //             pid: pid
  //           }
  //         }).then((res) => {
  //           const {
  //             data
  //           } = res.data;
  //           if (res.data.code == 0) {
  //             //登录成功存储用户信息
  //             app.setLogon(data, 1, () => {
  //               //登录后跳转

  //               $toast(`登录成功`, {
  //                 icon: 'success',
  //                 times: 1000,
  //               }).then(() => {
  //                 //wxApi.switchTab(getPage.home);
  //                 wxApi.refreshPage();
  //               })
  //             });
  //           } else {
  //             $toast(res.errmsg);
  //           }
  //         });
  //       } else {
  //         console.log('登录失败！' + res.data.errMsg)
  //       }
  //     }
  //   })
  // },

  /**
   * 右上角分享事件
   */
  onShareAppMessage(res) {


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.videoContext = wx.createVideoContext('myVideo')
  },

  onPlay(e) {
    this.setData({
      isShowPlayButton: true
    })
    this.videoContext.play()
  },
  ended(e) {
    // console.log('ended', e);
    this.setData({
      isShowPlayButton: false
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.hideHomeButton();
    wx.hideShareMenu({
      success: (res) => {},
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})